package org.example.demo1;

import com.google.gson.Gson;
import dao.StudentDao;
import pojo.Student;

import java.io.*;
import java.util.HashMap;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet(name = "helloServlet", value = "/hello-servlet")
public class HelloServlet extends HttpServlet {
    private Student student;

    public void init() {
         student = new Student("id","username","null","null",0);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse resp) throws IOException {
// 防止乱码
       resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html");
        student.setSid(request.getParameter("sid"));
        student.setSname( request.getParameter("sname"));
        student.setSsex(request.getParameter("ssex"));
        student.setSphone(request.getParameter("sphone"));
        String sageParam = request.getParameter("sage");
        int sage;
        if (sageParam != null && !sageParam.isEmpty()) {
            try {
                sage = Integer.parseInt(sageParam);
                student.setSage(sage);
            } catch (NumberFormatException e) {
                // 处理不合法的sage参数情况，例如返回错误信息或日志记录
                HashMap<String, Object> errorRs = new HashMap<>();
                errorRs.put("code", 400);
                errorRs.put("msg", "年龄参数必须是有效的整数");
                Gson gson = new Gson();
                resp.getWriter().println(gson.toJson(errorRs));
                return; // 结束方法，不再执行后续添加学生的逻辑
            }
        } else {
            // 缺少sage参数或为空的处理，也可以选择设定一个默认值或者返回错误信息
            HashMap<String, Object> errorRs = new HashMap<>();
            errorRs.put("code", 400);
            errorRs.put("msg", "年龄参数缺失");
            Gson gson = new Gson();
            resp.getWriter().println(gson.toJson(errorRs));
            return;
        }
        student.setSage(sage);
        StudentDao studentDao = new StudentDao();
        int flag = studentDao.addStudents(student);
//        创造一个hashmap
        HashMap<String, Object> rs = new HashMap<>();
        if (flag>0){
            rs.put("code",200);
            rs.put("msg","添加成功");
            rs.put("data",1);
        }else {
            rs.put("code",500);
            rs.put("msg","添加失败");
        }
//        使用gson产生json数据
        Gson gson = new Gson();
        String jsonResponse = gson.toJson(rs);
        resp.getWriter().println(jsonResponse);

    }

    public void destroy() {
    }
}